﻿/*
Copyright (c) 2010 The Developer Journey Company

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
THE SOFTWARE. 
*/

using System;
using System.ComponentModel;
using System.Text;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Linq;
using System.Xml.Linq;
using System.Device.Location;
using CommunityMegaphone.Models;

namespace CommunityMegaphone.ViewModels
{
    public class SearchResultsViewModel : NotifyPropertyChangedBase
    {
        public event Action SearchStarted;
        private void FireSearchStartedEvent()
        {
            if (SearchStarted == null)
                return;
            SearchStarted();
        }

        public event Action SearchCompleted;
        private void FireSearchCompletedEvent()
        {
            if (SearchCompleted == null)
                return;
            SearchCompleted();
        }

        public SearchResultsViewModel()
        {
            FilteredEventTypes = 
                new ObservableCollection<EventTypeViewModel>();
            FilteredStates = 
                new ObservableCollection<StateViewModel>();
            LoadFilterData();

            Events = new ObservableCollection<EventViewModel>();
            NoEvents = new ObservableCollection<EventViewModel>();
            ReloadEvents();
        }

        public ObservableCollection<EventViewModel> Events
        {
            get;
            private set;
        }

        private ObservableCollection<EventViewModel> NoEvents { get; set; }

        public SearchType SearchType { get; set; }
        public string SearchCityName { get; set; }
        public string PostalCode { get; set; }

        public ObservableCollection<EventTypeViewModel> FilteredEventTypes
        {
            get;
            private set;
        }

        private string EventTypeFilter
        {
            get
            {
                if (FilteredEventTypes == null
                    || FilteredEventTypes.Count == 0)
                    return null;
                return FilteredEventTypes
                    .Select(fet => fet.ID.Trim()).Join(',');
            }
        }

        public ObservableCollection<StateViewModel> FilteredStates
        {
            get;
            private set;
        }

        private string StateFilter
        {
            get
            {
                if (FilteredStates == null || FilteredStates.Count == 0)
                    return null;
                return FilteredStates.Select(fs => fs.Code.Trim()).Join(',');
            }
        }

        public void ReloadEvents(bool forceRefresh = false)
        {
            ReadEventsXml(forceRefresh);
        }

        public void ReloadEvents(GeoCoordinate center)
        {
            ReadEventsXml(center);
        }

        public void LoadFilterData()
        {
            // simulate some reference data
            //FilteredEventTypes.Add(new EventTypeViewModel() { ID = "CC", InPerson = true, Name = "Code Camp" });
            //FilteredEventTypes.Add(new EventTypeViewModel() { ID = "FS", InPerson = true, Name = "Firestarter" });
            //FilteredEventTypes.Add(new EventTypeViewModel() { ID = "UG", InPerson = true, Name = "User Group" });
            //FilteredStates.Add(new StateViewModel() { Code = "MD", Name = "Maryland" });
            //FilteredStates.Add(new StateViewModel() { Code = "NC", Name = "North Carolina" });
            //FilteredStates.Add(new StateViewModel() { Code = "VA", Name = "Virginia" });
        }

        private static void WriteEventsXml(string xml)
        {
            if (xml == null || xml.Length == 0)
                return;
            IsolatedStorageFile stg = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFileStream stream = stg.OpenFile("events.xml",
                FileMode.Create, FileAccess.Write, FileShare.None))
            {
                byte[] data = UTF8Encoding.UTF8.GetBytes(xml);
                stream.Write(data, 0, data.Length);
            }
        }

        private void ReadEventsXml(GeoCoordinate center)
        {
            Events = NoEvents;
            NotifyPropertyChanged("Events");
            try
            {
                IsolatedStorageFile stg = IsolatedStorageFile.GetUserStoreForApplication();
                if (stg.FileExists("events.xml"))
                    stg.DeleteFile("events.xml");

                WebClient client = new WebClient();
                client.DownloadStringCompleted += OnDownloadXmlCompleted;

                var query = new ODataQueryBuilder()
                {
                    EventTypeFilter = this.EventTypeFilter,
                    StateFilter = this.StateFilter,
                    PageSize = 24
                }.GetEventsByDistanceURL((float)center.Latitude, (float)center.Longitude, 100);
                client.DownloadStringAsync(new Uri(query));
            }
            catch { }
        }

        private void ReadEventsXml(bool reload = false)
        {
            Events = NoEvents;
            NotifyPropertyChanged("Events");
            try
            {
                IsolatedStorageFile stg = IsolatedStorageFile.GetUserStoreForApplication();
                if (reload)
                {
                    if (stg.FileExists("events.xml"))
                        stg.DeleteFile("events.xml");
                }
                if (stg.FileExists("events.xml"))
                {
                    // read the last known XML from the service
                    using (var stream = stg.OpenFile("events.xml",
                        FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        if (stream.Length <= Int32.MaxValue)
                        {
                            int length = (int)stream.Length;
                            byte[] data = new byte[length];
                            int read = stream.Read(data, 0, length);
                            if (read == length)
                            {
                                OnDownloadXmlCompleted(
                                    UTF8Encoding.UTF8.GetString(data, 0, length), null);
                            }
                        }
                    }
                }
                else
                {
                    // no cached XML - connect to the service
                    WebClient client = new WebClient();
                    client.DownloadStringCompleted += OnDownloadXmlCompleted;

                    var query = new ODataQueryBuilder()
                    {
                        EventTypeFilter = this.EventTypeFilter,
                        StateFilter = this.StateFilter,
                        PageSize = 200
                    }.ApprovedEventsURL();
                    client.DownloadStringAsync(new Uri(query));
                }
            }
            catch { }
        }

        private void OnDownloadXmlCompleted(object sender,
            DownloadStringCompletedEventArgs e)
        {
            string xml = (e == null) 
                ? sender as string 
                : (e.Error == null) 
                    ? e.Result 
                    : String.Empty;
            if (xml == null || xml.Trim().Length == 0)
                return;
            if (ParseEventsXml(xml) > 0 && e != null)
                WriteEventsXml(xml);
        }

        private int ParseEventsXml(string xml)
        {
            var atomFeed = XElement.Parse(xml);
            XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
            var entryProperties = 
                from entry in atomFeed.Descendants(m + "properties")
                let address = entry.Element(d + "address")
                let audienceid = entry.Element(d + "audienceid")
                let city = entry.Element(d + "city")
                let description = entry.Element(d + "description")
                let endtime = entry.Element(d + "endtime")
                let eventtype = entry.Element(d + "eventtype")
                let eventUrl = entry.Element(d + "eventUrl")
                let id = entry.Element(d + "id")
                let latlong = entry.Element(d + "latlong")
                let pubdate = entry.Element(d + "pubdate")
                let starttime = entry.Element(d + "starttime")
                let state = entry.Element(d + "state")
                let timezoneid = entry.Element(d + "timezoneid")
                let title = entry.Element(d + "title")
                let zip = entry.Element(d + "zip")
                select new Event()
                {
                    Address = (address == null) ? null : address.Value,
                    AudienceIDs = (audienceid == null)
                        ? null
                        : audienceid.Value.Split(',')
                            .Select(aid => aid.Trim())
                            .Where(aid => aid.Length > 0)
                            .Select(aid => Convert.ToInt32(aid))
                            .ToArray(),
                    City = (city == null) ? null : city.Value,
                    Description = (description == null) ? "" : description.Value.Replace("<br/>", " ").Replace("<br />", " ").Replace("&amp;","&"),
                    EndTime = (endtime == null) ? DateTime.MaxValue : DateTime.Parse(endtime.Value),
                    EventType = (eventtype == null) ? "Event" : eventtype.Value,
                    EventURL = (eventUrl == null) ? null : eventUrl.Value,
                    ID = (id == null) ? default(int) : Int32.Parse(id.Value),
                    LatLong = (latlong == null) ? null : latlong.Value,
                    PubDate = (pubdate == null) ? DateTime.MaxValue : DateTime.Parse(pubdate.Value),
                    StartTime = (starttime == null) ? DateTime.MinValue : DateTime.Parse(starttime.Value),
                    State = (state == null) ? "State" : state.Value,
                    TimezoneID = (timezoneid == null) ? default(int) : Int32.Parse(timezoneid.Value),
                    Title = (title == null) ? "No Title Provided" : title.Value.Replace("&amp;", "&"),
                    ZIP = (zip == null) ? null : zip.Value
                };
            var newEvents = new ObservableCollection<EventViewModel>();
            int count = 0;
            foreach (var entry in entryProperties)
            {
                newEvents.Add(new EventViewModel(entry));
                count++;
            }
            Events = newEvents;
            NotifyPropertyChanged("Events");
            return count;
        }
    }
}
